import {constantRoutes,asyncRoutes} from '@/router'
/**
 * 当前页面路径是否有权限
 * @param path 当前页面路径
 * @param routes 后台获取的路由
 */
function hasPermission(path, routes) {
	let res = {
		onoff: false, //当前是否有匹配的路径
		data: '', //当前匹配到时的参数
	}
	routes.forEach(route => {
		if ('/' + route.url == path) {
			res.onoff = true
			res.data = {
				...route
			}
		} else {
			if (route.children) {
				route.children = hasPermission(path, routes)
			} else {
				res.onoff = false
				res.data = ''
			}
		}
	})
	return res
}

/**
 * 递归过滤异步路由表
 * @param routes  后台获取的路由
 * @param asyncRoutes 前端定义的全部路由
 */
export function filterAsyncRoutes(routes,asyncRoutes) {
	const res = []
	asyncRoutes.forEach(roter=>{
		//这里记得浅拷贝一下否则路由会被覆盖
		const tmp = { ...roter }
		routes.forEach(item=>{
			if(tmp.name==item.url){
				if(item.children&&item.children.length>0){
					tmp.children=filterAsyncRoutes(item.children,tmp.children) 
				}
				//把前端定义的一些值替换成后台动态获取的
				tmp.meta.id=item.id
				tmp.meta.icon=item.icon
				tmp.meta.title=item.name
				res.push(tmp)
			}
		})
	})
	return res
}

const state = {
	routes: [],//所有有权限的路由【包含前端可访问的页面如404】
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.routes = routes
	}
}

const actions = {
	generateRoutes({
		commit
	}, routes) {
		return new Promise(resolve => {
			let accessedRoutes = filterAsyncRoutes(routes,asyncRoutes)
			let newRouter=constantRoutes.concat(accessedRoutes)
			console.log('最后获取到的权限菜单', newRouter);
			commit('SET_ROUTES', newRouter)
			resolve(newRouter)
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
